package com.example.javawebdemo.servlets;
//ProductServlet.java

import com.example.javawebdemo.command.CommandFactory;
import com.example.javawebdemo.command.ProductCommand;
import com.example.javawebdemo.dao.DAOFactory;
import com.example.javawebdemo.dao.ProductDAO;
import com.example.javawebdemo.models.Product;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/products")
public class ProductServlet extends HttpServlet {

    // 声明DAO成员变量
    private ProductDAO productDAO;

    @Override
    public void init() throws ServletException {
        // 通过工厂类初始化DAO
        productDAO = DAOFactory.getProductDAO();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");
        ProductCommand command = CommandFactory.getCommand(action);
        try {
            command.execute(request, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
//        try {
//            if (action == null) {
//                listProducts(request, response);
//            } else {
//                switch (action) {
//                    case "new":
//                        request.getRequestDispatcher("/WEB-INF/views/add-product.jsp").forward(request, response);
//                        break;
//                    case "edit":
//                        showEditForm(request, response);
//                        break;
//                    case "delete":
//                        deleteProduct(request, response);
//                        break;
//                }
//            }
//        } catch (SQLException ex) {
//            throw new ServletException(ex);
//        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");
        try {
            if (action != null) {
//                UserDAO userDAO = DAOFactory.getUserDAO();
                listProducts(request, response);
                switch (action) {
                    case "add":
                        addProduct(request);
                        response.sendRedirect("products");
                        break;
                    case "update":
                        // 修正调用参数增加response
                        updateProduct(request,response);
                        response.sendRedirect("products");
                        break;
                }
            }
        } catch (SQLException ex) {
            throw new ServletException(ex);
        }
    }


    // 统一保留带验证逻辑的updateProduct方法，并修正参数增加response
    private void updateProduct(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        try {
            Product product = new Product();
            product.setId(Integer.parseInt(request.getParameter("id")));

            String priceStr = request.getParameter("price");
            String stockStr = request.getParameter("stock");

            if (priceStr == null || stockStr == null ||
                    priceStr.isEmpty() || stockStr.isEmpty()) {
                throw new IllegalArgumentException("价格和库存不能为空");
            }

            double price = Double.parseDouble(priceStr);
            int stock = Integer.parseInt(stockStr);

            if (price <= 0 || stock < 0) {
                throw new IllegalArgumentException("价格必须大于零，库存不能为负数");
            }

            product.setName(request.getParameter("name"));
            product.setPrice(price);
            product.setStock(stock);
            product.setDescription(request.getParameter("description"));
            product.setImageUrl(request.getParameter("imageUrl"));

            productDAO.updateProduct(product);

        } catch (NumberFormatException e) {
            request.setAttribute("errorMessage", "输入格式不正确，请检查数字格式");
            forwardToEditForm(request, response);
        } catch (IllegalArgumentException e) {
            request.setAttribute("errorMessage", e.getMessage());
            forwardToEditForm(request, response);
        }
    }

    private void forwardToEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        int id = Integer.parseInt(request.getParameter("id"));
        Product product = productDAO.getProductById(id);
        request.setAttribute("product", product);
        request.getRequestDispatcher("edit-product.jsp").forward(request, response);
    }

//    private void listProducts(HttpServletRequest request, HttpServletResponse response, ProductDAO productDAO)
//            throws SQLException, ServletException, IOException {
//        List<Product> products = productDAO.getAllProducts();
//        request.setAttribute("products", products);
//        request.getRequestDispatcher("/WEB-INF/views/products.jsp").forward(request, response);
//    }

    private void listProducts(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        List<Product> products = productDAO.getAllProducts();
        request.setAttribute("products", products);
        request.getRequestDispatcher("products.jsp").forward(request, response);
    }


    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Product product = productDAO.getProductById(id);
        request.setAttribute("product", product);
        request.getRequestDispatcher("edit-product.jsp").forward(request, response);
    }

    private void deleteProduct(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        productDAO.deleteProduct(id);
        response.sendRedirect("products");
    }

    private void addProduct(HttpServletRequest request)
            throws SQLException {
        Product product = new Product();
        product.setName(request.getParameter("name"));
        product.setPrice(Double.parseDouble(request.getParameter("price")));
        product.setStock(Integer.parseInt(request.getParameter("stock")));
        product.setDescription(request.getParameter("description"));
        product.setImageUrl(request.getParameter("imageUrl"));
        productDAO.addProduct(product);
    }
}
